//
//  CameraViewController.m
//  Sight
//
//  Created by chenheren on 16/8/3.
//  Copyright © 2016年 chen. All rights reserved.
//

#import "CameraViewController.h"
#import <AVFoundation/AVFoundation.h> //相机
#import <AssetsLibrary/AssetsLibrary.h>  //相册
#import <GPUImage/GPUImage.h>
#import <Photos/Photos.h>
#import "FilterListCell.h"
#import "GPUImageBeautifyFilter.h"
#import "AlbumViewController.h"



#define kMainScreenWidth [UIScreen mainScreen].bounds.size.width
#define kMainScreenHeight [UIScreen mainScreen].bounds.size.height

static NSString *FilterListCellIdentifier =@"FilterListCellIdentifier";

typedef NS_ENUM(NSInteger,CameraManageFlashMode){
    CameraManageFlashModeAuto,
    CameraManageFlashModeOff,
    CameraManageFlashModeOn
};

@interface CameraViewController ()<UICollectionViewDelegate,UICollectionViewDataSource,UICollectionViewDelegateFlowLayout>
{
    CALayer *_focusLayer; //聚焦层
    UIImage *currentImage;
}

@property (strong, nonatomic) IBOutlet UIButton *grabButton;
@property (strong,nonatomic) NSDictionary *FilterClassName;  //滤镜列表

@property (nonatomic,strong) GPUImageStillCamera *cameraManager; //新建相机cameraManager

//根据storyboard上将界面分为三个View，预览View，底部View以及整体的cameraView,也可以用代码实现
@property (strong, nonatomic) IBOutlet UIView *cameraView;

@property (strong, nonatomic) IBOutlet UICollectionView *FilterCollectionView;

@property (nonatomic , weak) IBOutlet UIButton *flashButton;//闪光灯按钮


@property (strong, nonatomic) IBOutlet UIButton *albumButton;
@property (nonatomic , assign) CameraManageFlashMode flashMode;

@property (nonatomic , assign) CGFloat beginGestureScale;//开始的缩放比例

@property (nonatomic , assign) CGFloat effectiveScale;//最后的缩放比例

@property GPUImageOutput *selectedFilter;//滤镜

@property GPUImageView *filterView;//实时滤镜预览视图

@property AVCaptureStillImageOutput *photoOutput;//用于保存原图

@end

@implementation CameraViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    
    [self setUpUI];
    
    [self initFilters];
    
    
    
    //初始化相机，默认为前置相机
    _cameraManager = [[GPUImageStillCamera alloc] initWithSessionPreset:AVCaptureSessionPresetPhoto cameraPosition:AVCaptureDevicePositionFront];
    _cameraManager.outputImageOrientation = UIInterfaceOrientationPortrait;//设置照片的方向为设备的定向
    _cameraManager.horizontallyMirrorFrontFacingCamera = YES;//设置是否为镜像
    _cameraManager.horizontallyMirrorRearFacingCamera = NO;
    
    _selectedFilter = [[NSClassFromString([[self.FilterClassName allKeys]objectAtIndex:0]) alloc]init];//初始化滤镜，默认初始化为原图GPUImageFilter
    
    /**
     *设置cameraManager的输出对象为filter,然后将preview强制转换为filterView添加到filter的输出对象中，这样在filterView中显示的就是相机捕捉到的并且经过filter滤镜处理的实时图像了
     */
    [self.cameraManager addTarget:_selectedFilter];
    _filterView = (GPUImageView *)self.cameraView;
    [_selectedFilter addTarget:_filterView];
    
    //初始化闪光灯模式为Auto
    [self setFlashMode:CameraManageFlashModeAuto];

    //初始化开始及结束的缩放比例都为1.0
    [self setBeginGestureScale:1.0f];
    [self setEffectiveScale:1.0f];
    //启动相机捕获
    [self.cameraManager startCameraCapture];
    
    
    
}

#pragma mark - setupUI

-(void)setUpUI{
    [self.grabButton setTitle:@"||" forState:UIControlStateNormal];
    [self.FilterCollectionView setBackgroundColor:[UIColor whiteColor]];
    
    [self.FilterCollectionView registerNib:[UINib nibWithNibName:@"FilterListCell" bundle:nil] forCellWithReuseIdentifier:FilterListCellIdentifier];
    [self getLatestPhoto]; //加载最新照片并且显示
}

-(void)initFilters{
    
    self.FilterClassName = @{NSStringFromClass([GPUImageFilter class]):@"正常",
                             NSStringFromClass([GPUImageBeautifyFilter class]):@"美颜",
                             NSStringFromClass([GPUImageGammaFilter class]):@"灰度",
                             NSStringFromClass([GPUImageSepiaFilter class]):@"怀旧",
                             NSStringFromClass([GPUImageSketchFilter class]):@"素描",
                             NSStringFromClass([GPUImagePixellateFilter class]):@"像素化",
                             NSStringFromClass([GPUImageColorInvertFilter class]):@"反转",
                             NSStringFromClass([GPUImageToonFilter class]):@"卡通",
                             NSStringFromClass([GPUImageRGBErosionFilter class]):@"腐蚀"};
    
}

#pragma mark - UICollectionView Delegate

-(NSInteger)numberOfSectionsInCollectionView:(UICollectionView *)collectionView{
    return 1;
}

-(NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section{
    return [self.FilterClassName count];
}

-(UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath{
    
    FilterListCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:FilterListCellIdentifier forIndexPath:indexPath];
    cell.backgroundColor = [UIColor whiteColor];
    GPUImageFilter *filter = [[NSClassFromString([[self.FilterClassName allKeys]objectAtIndex:indexPath.item]) alloc]init];
    UIImage *filteredimage = [filter imageByFilteringImage:[UIImage imageNamed:@"demo.jpg"]];
    
    cell.imageView.image = filteredimage;

    cell.label.text = [self.FilterClassName allValues][indexPath.item];
    
    return cell;
}

-(CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout sizeForItemAtIndexPath:(NSIndexPath *)indexPath{
    CGFloat height = self.FilterCollectionView.frame.size.height;
    CGFloat witdh = height *9/16.0;
    return  CGSizeMake(witdh, height-20);  //减去上下边距
}

-(UIEdgeInsets)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout insetForSectionAtIndex:(NSInteger)section{
    UIEdgeInsets edgeInset = UIEdgeInsetsMake(10, 10, 10, 10);
    return edgeInset;
}

-(CGFloat)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout minimumLineSpacingForSectionAtIndex:(NSInteger)section{
    return 10;
}



- (IBAction)goBackButtonPressed:(id)sender {
    [self dismissViewControllerAnimated:YES completion:nil];
}

#pragma mark - Latest photo

/**
 *  获取相册最新照片
 */
-(void)getLatestPhoto{
    PHFetchOptions *options = [[PHFetchOptions alloc] init];
    options.sortDescriptors = @[[NSSortDescriptor sortDescriptorWithKey:@"creationDate" ascending:NO]];
    PHFetchResult *assetsFetchResults = [PHAsset fetchAssetsWithOptions:options];
    PHCachingImageManager *imageManager = [[PHCachingImageManager alloc] init];
    [imageManager requestImageForAsset:assetsFetchResults[0]
                            targetSize:CGSizeMake(50, 50)
                           contentMode:PHImageContentModeAspectFill
                               options:nil
                         resultHandler:^(UIImage *result, NSDictionary *info) {
                             
                             currentImage = [result copy];
                             
                             [self.albumButton setBackgroundImage:result forState:UIControlStateNormal];
                             
                         }];

}

- (IBAction)openAlbum:(id)sender {
    AlbumViewController *albumViewController = [[AlbumViewController alloc]init];
    albumViewController.currentImage = currentImage;
    [self presentViewController:albumViewController animated:YES completion:nil];
}


-(void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath{
    UICollectionViewCell *cell = [collectionView cellForItemAtIndexPath:indexPath];
    cell.backgroundColor = [UIColor colorWithRed:37/255.0f green:175/255.0f blue:148/255.0f alpha:1.0f];
}

-(void)collectionView:(UICollectionView *)collectionView didDeselectItemAtIndexPath:(NSIndexPath *)indexPath{
    UICollectionViewCell *cell = [collectionView cellForItemAtIndexPath:indexPath];
    cell.backgroundColor = [UIColor whiteColor];
    
}

- (IBAction)grab:(id)sender {
    
    [self.cameraManager capturePhotoAsImageProcessedUpToFilter:[[GPUImageSketchFilter alloc]init] withOrientation:UIImageOrientationUp withCompletionHandler:^(UIImage *processedImage, NSError *error) {
            UIImageWriteToSavedPhotosAlbum(processedImage , self,nil, nil);
            [self getLatestPhoto];
    }];
    
    
}
@end
